package table_image

import (
	"fmt"
	"time"

	"gitee.com/klein-x/biz/model/mysql/table"
	"gitee.com/klein-x/biz/module/db/mysql"
	"gorm.io/gorm"
)

/*
说明： 类七牛云的一个图片存储库
    图片以uuid作为主键进行存储，内容为base64转码后的数据
*/

type Resource struct {
	UUID      string         `gorm:"primaryKey;type:char(36);unique;not null;comment:'UUID'"`
	Type      string         `gorm:"type:char(1);not null;comment:'资源类型,image 1'"`
	Data      string         `gorm:"type:longtext;not null;comment:'资源数据'"`
	CreatedAt time.Time      `gorm:"not null;comment:'创建时间'"`
	UpdatedAt time.Time      `gorm:"not null;comment:'更新时间'"`
	DeletedAt gorm.DeletedAt `gorm:"comment:'软删除时间'"`
}

func (i *Resource) TableName() string {
	return "resource"
}

func ResourceGetById(UUID string) (*Resource, error) {
	db := mysql.GetGlobalDB()

	var res Resource
	return table.SelectCheck(&res, db.Where("uuid = ?", UUID).Find(&res))
	// result :=
	// if result.Error != nil {
	// 	return res, result.Error
	// }

	// if result.RowsAffected == 0 {
	// 	return res, fmt.Errorf("no record found with UUID %s", UUID)
	// }

	// return res, nil
}

func ResourceInsertById(UUID string, resType string, resData string) error {
	db := mysql.GetGlobalDB()

	var res Resource
	res.UUID = UUID
	res.Type = resType
	res.Data = resData

	// 尝试插入记录
	result := db.Create(&res)

	// 检查是否有错误发生
	if result.Error != nil {
		return result.Error
	}

	return nil
}

func ResourceUpdateById(UUID string, resType string, resData string) error {
	db := mysql.GetGlobalDB()

	// 构建更新的数据
	updateData := map[string]interface{}{
		"Type": resType,
		"Data": resData,
	}

	// 执行更新操作
	result := db.Model(&Resource{}).Where("UUID = ?", UUID).Updates(updateData)

	// 检查是否有错误发生
	if result.Error != nil {
		return result.Error
	}

	// 检查是否更新了任何记录
	if result.RowsAffected == 0 {
		return fmt.Errorf("no record found with UUID %s", UUID)
	}

	return nil
}

func ResourceDeleteById(UUID string) error {
	db := mysql.GetGlobalDB()

	// 执行删除操作
	result := db.Delete(&Resource{}, UUID)

	// 检查是否有错误发生
	if result.Error != nil {
		return result.Error
	}

	// 检查是否删除了任何记录
	if result.RowsAffected == 0 {
		return fmt.Errorf("no record found with UUID %s", UUID)
	}

	return nil
}
